import { createBrowserRouter, RouteObject } from 'react-router-dom';
import Layout from '@/layout';
import Login, { loginLoader } from '@/pages/login';
import NotFound from '@/pages/notFound';
import Demo, { Store } from '@/pages/demo';

const defaultRoutes: Routes[] = [
  {
    id: 'root',
    path: '/',
    Component: Layout,
    // loader: layoutLoader,
    children: [
      {
        path: 'test',
        Component: NotFound,
      },
    ],
  },
  {
    path: '*',
    Component: NotFound,
  },
  {
    path: 'login',
    loader: loginLoader,
    Component: Login,
  },
  {
    path: 'demo',
    Component: Demo,
    children: [
      {
        path: ':id',
        Component: Store,
      },
    ],
  },
];

type Routes = RouteObject;
export const routes: Routes[] = [];
export type IModule = {
  [name: string]: {
    default: () => JSX.Element;
  };
};
const modules: IModule = import.meta.glob('@/pages/**/index.tsx', { eager: true });
for (const path in modules) {
  const pathName = path.split('/')[3];
  const blackList = ['notFound'];
  if (!blackList.includes(pathName)) {
    const Component = () => modules[path].default();
    routes.push({
      index: pathName == 'home' ? true : false,
      path: pathName == 'home' ? undefined : pathName,
      element: <Component />,
    });
  }
}

const generateRoutes = () => {
  const existPaht = defaultRoutes.map((i) => i.path);
  const root: any = defaultRoutes.find((i) => i.id == 'root');
  root.children = routes.filter((i) => !existPaht.includes(i.path as string));
  return defaultRoutes;
};

const router = createBrowserRouter(defaultRoutes);

export default router;
